package com.weavernorth.humanresource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Element;
import sun.misc.BASE64Encoder;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import static com.weavernorth.humanresource.util.commonUtil.getLzyysmCode;

/**
 * Created by guo_zy on 2019/12/24.
 * 离职
 */
public class personnelQuit implements Action {
    public static Log log = LogFactory.getLog(personnelQuit.class.getName());

    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        SalarRangeUtil salarRangeUtil=new SalarRangeUtil();
        String fhz = "";
        String requestid = requestInfo.getRequestid();//请求ID
        //String workflowid = requestInfo.getWorkflowid();//流程ID
        String tablename = requestInfo.getRequestManager().getBillTableName();//表单名称
        //提示信息
        String strMessage = "";
        String sygbh = "";//员工编号
        String slzrq = "";//离职日期
        String sczlx = "";//操作类型
        String sczyy = "";//操作原因
        String sjhlzrq = "";//计划离职日期
        String ssbzhjnrq = "";//社保最后缴纳日期
        String slzlb = "";//离职类别
        String slzyy = "";//离职原因
        String slzms = "";//离职描述
        String ssfzcly = "";//是否再次录用
        String sjrhmdyy = "";//加入黑名单原因
        String strZlzyysm="";//离职原因说明

        String sql = " select lzyysm,ygbh,lzrq,czlx,czyy,jhlzrq,sbzhjnrq,lzlb,lzyy,lzms,sfzcly,jrhmdyy,gzfw from " + tablename + " where requestid =" + requestid;
        rs.execute(sql);//确保只有1条记录
        if (rs.getCounts() != 1) {
            return FAILURE_AND_CONTINUE;
        }
        while (rs.next()) {
            strZlzyysm=getLzyysmCode(Util.null2String(rs.getString("lzyysm")));
            //工资核算范围id
            String strGzfw=Util.null2String(rs.getString("gzfw"));
            //工资核算范围bpm值
            String strGzhsfw=salarRangeUtil.getGzfw(strGzfw);
            //离职日期
            slzrq = rs.getString("lzrq");
            //zm 增加,判断工资范围是否锁定 开始

            String strLockMess = salarRangeUtil.judgeLock(strGzhsfw, slzrq);
            log.info("工资核算范围返回信息:" + strLockMess);
            if (!"".equals(strLockMess)) {
                strLockMess=strLockMess+"薪资核算结束后，工资范围解除锁定，流程可以继续提交";
                requestInfo.getRequestManager().setMessagecontent(strLockMess);
                return FAILURE_AND_CONTINUE;

            }

            //循环语句必须，虽然只有1条记录
            sygbh = rs.getString("ygbh");//员工编号

            sczlx = "";//rs.getString("czlx");//操作类型
            sczyy = "";//rs.getString("czyy");//操作原因
            sjhlzrq = rs.getString("jhlzrq");//计划离职日期
            ssbzhjnrq = rs.getString("sbzhjnrq");//社保最后缴纳日期
            slzlb = rs.getString("lzlb");//离职类别
            slzyy = ""; //= rs.getString("lzyy");//离职原因
            slzms = rs.getString("lzms");//离职描述
            ssfzcly = rs.getString("sfzcly");//是否再次录用
            sjrhmdyy = rs.getString("jrhmdyy");//加入黑名单原因

            if (slzlb.equals("0")) {
                slzlb = "10";
            } else if (slzlb.equals("1")) {
                slzlb = "20";
            }
            if (ssfzcly.equals("0")) {
                ssfzcly = "10";
            } else if (ssfzcly.equals("1")) {
                ssfzcly = "20";
            }
            switch (rs.getString("lzyy")) {
                case "0":
                    slzyy = "80";
                    break;
                case "1":
                    slzyy = "84";
                    break;
                case "2":
                    slzyy = "88";
                    break;
                case "3":
                    slzyy = "92";
                    break;
                case "4":
                    slzyy = "94";
                    break;
                case "5":
                    slzyy = "10";
                    break;
                case "6":
                    slzyy = "20";
                    break;
                case "7":
                    slzyy = "30";
                    break;
                case "8":
                    slzyy = "40";
                    break;
                case "9":
                    slzyy = "50";
                    break;
                case "10":
                    slzyy = "60";
                    break;
                case "11":
                    slzyy = "70";
                    break;
                default:
                    slzyy = "";
            }
            switch (rs.getString("czlx")) {
                case "0":
                    sczlx = "Z4";
                    break;
                case "1":
                    sczlx = "Z5";
                    break;
                case "2":
                    sczlx = "ZA";
                    break;
                case "3":
                    sczlx = "ZB";
                    break;
                case "4":
                    sczlx = "ZF";
                    break;
                default:
                    sczlx = "";
            }
            switch (rs.getString("czyy")) {
                case "0":
                    sczyy = "10";
                    break;
                case "1":
                    sczyy = "20";
                    break;
                case "2":
                    sczyy = "30";
                    break;
                case "3":
                    sczyy = "40";
                    break;
                case "4":
                    sczyy = "50";
                    break;
                case "5":
                    sczyy = "60";
                    break;
                case "6":
                    sczyy = "70";
                    break;
                case "7":
                    sczyy = "10";
                    break;
                case "8":
                    sczyy = "10";
                    break;
                case "9":
                    sczyy = "20";
                    break;
                case "10":
                    sczyy = "30";
                    break;
                case "11":
                    sczyy = "40";
                    break;
                case "12":
                    sczyy = "50";
                    break;
                case "13":
                    sczyy = "10";
                    break;
                case "14":
                    sczyy = "10";
                    break;
                default:
                    sczyy = "";
            }

        }
        StringBuffer xml = new StringBuffer("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:rfc:functions\">");
        xml.append("<soapenv:Header/>");
        xml.append("<soapenv:Body>");
        xml.append("<urn:ZHRI_070>");
        xml.append("<I_BEGDA>" + slzrq + "</I_BEGDA>");
        xml.append("<I_MASSG>" + sczyy + "</I_MASSG>");
        xml.append("<I_MASSN>" + sczlx + "</I_MASSN>");
        xml.append("<I_PERNR>" + sygbh + "</I_PERNR>");
        xml.append("<I_ZBLYYN><![CDATA[" + sjrhmdyy + "]]></I_ZBLYYN>");
        xml.append("<I_ZJHLZSJ>" + sjhlzrq + "</I_ZJHLZSJ>");
        xml.append("<I_ZLZLX>" + slzyy + "</I_ZLZLX>");
        xml.append("<I_ZLZMS><![CDATA[" + slzms + "]]></I_ZLZMS>");
        xml.append("<I_ZLZYY>" + slzlb + "</I_ZLZYY>");
        xml.append("<I_ZSBDAT>" + ssbzhjnrq + "</I_ZSBDAT>");
        xml.append("<I_ZSFZCLY>" + ssfzcly + "</I_ZSFZCLY>");
//        <![CDATA["+strDate+"]]>
        //region [==新增字段-2021-03-04==]
        xml.append("<I_ZLZHMDYY></I_ZLZHMDYY>");
        xml.append("<I_ZLZYYSM>"+strZlzyysm+"</I_ZLZYYSM>");
        //endregion

        xml.append("<RETURN>");
        xml.append("<item>");
        xml.append("<TYPE></TYPE>");
        xml.append("<ID></ID>");
        xml.append("<NUMBER></NUMBER>");
        xml.append("<MESSAGE></MESSAGE>");
        xml.append("<LOG_NO></LOG_NO>");
        xml.append("<LOG_MSG_NO></LOG_MSG_NO>");
        xml.append("<MESSAGE_V1></MESSAGE_V1><MESSAGE_V2></MESSAGE_V2><MESSAGE_V3></MESSAGE_V3><MESSAGE_V4></MESSAGE_V4>");
        xml.append("<PARAMETER></PARAMETER>");
        xml.append("<ROW></ROW>");
        xml.append("<FIELD></FIELD>");
        xml.append("<SYSTEM></SYSTEM>");
        xml.append("</item></RETURN>");
        xml.append("</urn:ZHRI_070>");
        xml.append("</soapenv:Body>");
        xml.append("</soapenv:Envelope>");
        log.info("chuanshudexmlis:" + xml.toString());
        try {
            String lzUrl = bb.getPropValue("personnel-erdos", "lzurl");//获取配置文件信息
            String responseXml = sendPost(lzUrl, xml.toString(), "utf-8");
            log.info("lizhifanhuizhi:" + responseXml);//打印日志
            //解析返回值开始
            Document doc = null;
            try {
                doc = DocumentHelper.parseText(responseXml);
                Iterator<Element> its2= doc.selectNodes("//TYPE").iterator();
                while (its2.hasNext()){
                    Element element=its2.next();
                    fhz = element.getText();
                    if(!"".equals(fhz))
                        break;
                }

                //返回值失败时,则提示失败
                if ("E".equals(fhz)) {
                    Iterator<Element> its3 = doc.selectNodes("//MESSAGE").iterator();
                    while (its3.hasNext()) {
                        Element element2 = its3.next();
                        strMessage = element2.getText();
                        if (!"".equals(strMessage)) {
                            break;
                        }
                    }

                }

            } catch (DocumentException e) {
                e.printStackTrace();
            }//解析结束
        } catch (Exception e) {
            e.printStackTrace();
        }
		log.info("typefanhuizhi:"+fhz);
        if ("S".equals(fhz)) {
            return SUCCESS;
        }
        else {
            if (!"".equals(strMessage)) {
                requestInfo.getRequestManager().setMessagecontent(strMessage);
            }
            return FAILURE_AND_CONTINUE;
        }
    }

    public String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);

            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);
            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue("personnel-erdos", "username"));
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue("personnel-erdos", "password"));
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                // log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }
}

//    public static void main(String[] args) {
//        StringBuffer xml = new StringBuffer("<soap-env:Envelope xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>");
//        xml.append("<soap-env:Header/> <soap-env:Body>");
//        xml.append("<n0:ZHRI_070Response xmlns:n0='urn:sap-com:document:sap:rfc:functions'>");
//        xml.append("<RETURN>");
//        xml.append("<item><TYPE/><ID/><NUMBER>000</NUMBER><MESSAGE/><LOG_NO/><LOG_MSG_NO>000000</LOG_MSG_NO><MESSAGE_V1/><MESSAGE_V2/>");
//        xml.append("<MESSAGE_V3/><MESSAGE_V4/><PARAMETER/><ROW>0</ROW><FIELD/><SYSTEM/></item><item>");
//        xml.append("<TYPE>S</TYPE><ID/><NUMBER>000</NUMBER><MESSAGE>操作成功！</MESSAGE><LOG_NO/><LOG_MSG_NO>000000</LOG_MSG_NO>");
//        xml.append("<MESSAGE_V1/><MESSAGE_V2/><MESSAGE_V3/><MESSAGE_V4/><PARAMETER/><ROW>0</ROW><FIELD/><SYSTEM/></item></RETURN>");
//        xml.append("</n0:ZHRI_070Response></soap-env:Body></soap-env:Envelope>");
//        Document doc = null;
//        try {
//            doc = DocumentHelper.parseText(xml.toString());
//            Iterator<Element> its2= doc.selectNodes("//TYPE").iterator();
//            while (its2.hasNext()){
//                Element element=its2.next();
//                String HfqyjlpfMapper=element.getText();
//                System.out.println(HfqyjlpfMapper);
//            }
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }




